package com.swak.reactivex.p2p;

import java.io.File;
import java.io.Serializable;
import java.util.UUID;

import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.ResourceLoader;

import com.swak.Constants;
import com.swak.registry.URL;
import com.swak.serializer.JavaSerializer;
import com.swak.serializer.Serializer;
import com.swak.utils.FileUtils;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 端系统唯一 ID
 * 
 * @author 618lf
 */
@Deprecated
@Getter
@Setter
@Accessors(chain = true)
@EqualsAndHashCode(exclude = { "url" })
@ToString
public class PeerID implements Serializable {
	private static transient Serializer SERIALIZER = new JavaSerializer();
	private static transient ResourceLoader RESOURCE_LOADER = new FileSystemResourceLoader();
	private static final long serialVersionUID = 1L;
	private String id;
	private String url;

	public static PeerID localPeerID() {
		PeerID peerID = null;
		try {
			File runtime = RESOURCE_LOADER.getResource("file:.runtime/").getFile();
			if (!runtime.exists()) {
				runtime.mkdirs();
			}
			File peer = new File(runtime, "peerID");
			byte[] bytes = FileUtils.read(peer);
			peerID = (PeerID) SERIALIZER.deserialize(bytes);
			if (peerID == null) {
				peerID = new PeerID().setId(UUID.randomUUID().toString());
				bytes = SERIALIZER.serialize(peerID);
				FileUtils.write(peer, bytes);
			}
		} catch (Exception e) {
		}
		return peerID;
	}

	public static PeerID remotePeerID(URL url) {
		return new PeerID().setId(url.getParameter(Constants.Peer_Id)).setUrl(url.toFullString());
	}
}